package chen.videoedit;

import android.media.MediaCodec;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;

/**
 * 视频合成
 */
public class VideoJointActivity extends BasisActivity {
    private ArrayList<String> list;
    private String path_save;
    private MediaCodec.BufferInfo bufferInfo;
    private ArrayList<VideoPojo> VList;
    private MediaMuxer mediaMuxer;
    private int trackIndex;

    @Override
    public int setlayoutResID() {
        return R.layout.activity_video_joint;
    }

    @Override
    public void initialView(Bundle arg0) {
        findViewById(R.id.activity_video_joint_bt).setOnClickListener(this);

    }

    @Override
    public void setActivity() {
        path_save = Environment.getExternalStorageDirectory() + "/视频拼接.mp4";//音乐视频合成保持路径
        String video = Environment.getExternalStorageDirectory().getPath();//视频
        list = new ArrayList<>();
        list.add(video + "/1.mp4");
        list.add(video + "/2.mp4");
        list.add(video + "/3.mp4");
        list.add(video + "/4.mp4");
        bufferInfo = new MediaCodec.BufferInfo();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_video_joint_bt:
                MyThread thread = new MyThread();
                thread.start();
                break;
        }
    }


    private class MyThread extends Thread {
        @Override
        public void run() {
            addMediaExtractor();
            createMediaMuxer();
            readList();
            mediaMuxer.stop();
            mediaMuxer.release();
        }
    }


    /**
     * 创建MediaMuxer对象
     */
    private void createMediaMuxer() {
        try {
            mediaMuxer = new MediaMuxer(path_save, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        } catch (IOException e) {
            e.printStackTrace();
        }
        trackIndex = mediaMuxer.addTrack(VList.get(0).getVideoFormat());
        mediaMuxer.start();
    }


    /**
     * 遍历数据集合读取数据
     */
    private void readList() {
        for (VideoPojo pojo : VList) {
            readData(pojo);
        }
    }

    /**
     * 读取数据
     */
    private void readData(VideoPojo pojo) {
        MediaExtractor mediaExtractor = pojo.getMediaExtractor();
        mediaExtractor.selectTrack(pojo.getVideoTrack());
        MediaFormat mediaFormat = pojo.getVideoFormat();
        ByteBuffer inputBuffer = ByteBuffer.allocate(mediaFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE));//分配缓冲

        long videoSampleTime = 1000 * 1000 / 25;
        mediaExtractor.seekTo(0, MediaExtractor.SEEK_TO_PREVIOUS_SYNC); //选择起点
        Log.e("lll","开始");
        while (true) {
            inputBuffer.clear();
            int sampleSize = mediaExtractor.readSampleData(inputBuffer, 0);
            if (sampleSize < 0) {
                mediaExtractor.unselectTrack(pojo.getVideoTrack());   //这里一定要释放选择的轨道，不然另一个轨道就无法选中了
                break;
            }
            mediaExtractor.advance();
            int sampleFlag = mediaExtractor.getSampleFlags();  //获取帧类型，只能识别是否为I帧(关键帧)
            bufferInfo.offset = 0;
            bufferInfo.flags = sampleFlag; //是否关键帧
            bufferInfo.size = sampleSize;//数据长度
            bufferInfo.presentationTimeUs += videoSampleTime;//
            mediaMuxer.writeSampleData(trackIndex, inputBuffer, bufferInfo);
        }
        mediaExtractor.release();
        mediaExtractor = null;
    }


    /**
     * 创建MediaExtractor集合
     */
    private void addMediaExtractor() {
        VList = new ArrayList<VideoPojo>();
        for (String path : list) {
            createMediaExtractor(path);
        }
    }

    /**
     * 创建MediaExtractor
     */
    private void createMediaExtractor(String path) {
        MediaExtractor mediaExtractor = new MediaExtractor();//初始化分类器
        try {
            mediaExtractor.setDataSource(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        int Acount = mediaExtractor.getTrackCount();
        int videoTrack = 0;
        MediaFormat VideoMediaFormat = null;
        int audioTrack = 0;
        MediaFormat audioMediaFormat = null;
        for (int i = 0; i < Acount; i++) {
            MediaFormat format = mediaExtractor.getTrackFormat(i);
            String mime = format.getString(MediaFormat.KEY_MIME);
            if (mime.startsWith("video/")) {
                videoTrack = i;//音轨
                VideoMediaFormat = format;//音轨格式
            }
            if (mime.startsWith("audio/")) {
                audioTrack = i;//音轨
                audioMediaFormat = format;//音轨格式
            }
        }
        VideoPojo pojo = new VideoPojo();
        pojo.setMediaExtractor(mediaExtractor);
        pojo.setVideoTrack(videoTrack);
        pojo.setVideoFormat(VideoMediaFormat);
        pojo.setAudioFormat(audioMediaFormat);
        pojo.setAudioTrack(audioTrack);
        VList.add(pojo);
    }


}
